﻿using AutoMapper;
using MediatR;
using System.Linq;
using Reporting.API.Application.Commands.Productionorders;
using Reporting.API.DTOs.ProductionorderPlanDTO;
using Reporting.API.Utils;
using Reporting.Infrastructure.Interfaces.Productionorders;
using Reporting.Infrastructure.Interfaces.ProductionPlans;
using Reporting.Infrastructure.Interfaces.ProductTypes;
using Reporting.Errorcode.ErrorCode;

namespace Reporting.API.Application.CommandHandler.Productionorders
{
    public class SelectProductionorderCommandHandler : IRequestHandler<SelectProductionorderCommand, ApiResult<SelectProductionorderResponse>>
    {
        private readonly IProductionorderRepository _productionorderRepository;  //生产工单
        private readonly IProductTypeRepository _productTypeRepository;          //产品类型
        private readonly IProductionPlanRepository _productionPlanRepository;    //生产计划
        private readonly IMapper _mapper;
        private readonly ILogger<SelectProductionorderCommandHandler> _logger;

        public SelectProductionorderCommandHandler(IProductionorderRepository productionorderRepository, IMapper mapper, ILogger<SelectProductionorderCommandHandler> logger, IProductTypeRepository productTypeRepository, IProductionPlanRepository productionPlanRepository)
        {
            _productionorderRepository = productionorderRepository;
            _mapper = mapper;
            _logger = logger;
            _productTypeRepository = productTypeRepository;
            _productionPlanRepository = productionPlanRepository;
        }

        public async Task<ApiResult<SelectProductionorderResponse>> Handle(SelectProductionorderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取所有生产工单
                var Productionorders = await _productionorderRepository.GetAsync(x => x.Workordernumber == request.Workordernumber);
                //// 产品类型（外健）
                //var Sourcetype = await _productTypeRepository.GetAllAsync(y => y.ProductTypeID == Productionorders.ProductTypeID);
                //// 生产计划（外健）
                //var ProductionPlans = await _productionPlanRepository.GetAllAsync(a => a.Productionplanid == Productionorders.Productionplanid);

                // 使用 AutoMapper 进行对象映射
                var productionorderPlanResponses = _mapper.Map<SelectProductionorderResponse>(Productionorders);


                // 返回成功结果
                return ApiResult<SelectProductionorderResponse>.Success(productionorderPlanResponses, StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询失败");

                // 返回失败结果
                return ApiResult<SelectProductionorderResponse>.Fail("查询失败：" + ex.Message, StatusCodeEnum.BadRequest);
            }
        }
    }
}
